//自定义hook的作用适用于复用组件的逻辑,一般约定use开头,可以在不创建新的组件的情况下可以达到复用组件的效果

// type Icounter<T> = (initialValue: T) => any[]

import { useState } from "react"

type returnedValue = {
    increment: (val: number) => void
    decrement: (val: number) => void
}

//元组
type returned = [any, returnedValue]

function useCounter<T>(initialValue: T): returned {

    let [count, setCount] = useState<T>(initialValue)

    //这个自定义hook的需求是
    //1.提供的一个方法可以对初始值进行自加操作

    let increment = (val: number) => {

        //如果传递了val,那么count的就设置为用count和val相加
        //不然就让count自加1
        let v: any = val ? val + (count as number) : ++(count as number)

        setCount(v)
    }

    //2.提供的一个方法可以对初始值进行自减操作

    let decrement = (val: number) => {
        //如果传递了val,那么count的就设置为用count减去val
        //不然就让count自减1
        let v: any = val ? (count as number) - val : --(count as number)

        setCount(v)
    }

    return [count, { increment, decrement }]
}

export default useCounter
